package de.tum.in.eist.poll.server;

import java.util.concurrent.ConcurrentHashMap;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.tum.in.eist.poll.shared.Lecture;
import de.tum.in.eist.poll.shared.User;
import de.tum.in.eist.poll.shared.service.NotificationsPushService;

@SuppressWarnings("serial")
public class NotificationsPushServiceImpl extends RemoteServiceServlet
		implements NotificationsPushService {

	private static Object sema = new Object();

	private static ConcurrentHashMap<Integer,Lecture> notifications = new ConcurrentHashMap<Integer,Lecture>();
	private static ConcurrentHashMap<String, Integer> lastNotifications = new ConcurrentHashMap<String, Integer>();
	
	@Override
	public Lecture requestNotification(User u) {
		
		if(u == null)
			return null;
		
		if(!lastNotifications.containsKey(u.getKey()))
			lastNotifications.put(u.getKey(), notifications.size());
		
		synchronized (sema) {
			int last = lastNotifications.get(u.getKey());
			if(last >= notifications.size()){
				try {
					sema.wait(30000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(last < notifications.size()){
				Lecture notify = notifications.get(last);
				lastNotifications.put(u.getKey(), last+1);
				return notify;
			} else {
				return null;
			}
		}
	}

	public static void addNotification(Lecture l) {
		notifications.put(notifications.size(), l);
		synchronized (sema) {
			sema.notifyAll();
		}
	}

}
